<!-- GoodSku -->
<template>
  <div class="sku">
    <!-- 规格 -->
    <div class="sku-list-wrap">

      <!-- 规格类型 -->
      <div v-for="(item, $index) in attributeParamList" :key="$index" class="sku-lists">
        <div class="sku-name">
          <span class="sku-label">规格名：</span>
          <el-input :class="['sku-input', {'is-error': item.isError}]" :size="size" v-model="item.name" @change="handleDataChange(item)"></el-input>
          <!-- 规格名 name -->
          <el-checkbox v-if="$index === 0" class="sku-checkbox" v-model="item.havaIconChecked" @change="handleAddImg">添加规格图片</el-checkbox>
          <span class="sku-delete" @click="handleRemove(1, $index, item)">删除</span>
        </div>
        <div class="sku-value">
          <div>
            <span class="sku-label">规格值：</span>
            <span v-if="item.attributes.length >= 40" class="sku-add-value-ele add-disabled">规格值不超过{{skuValueLen}}个</span>
            <span v-else class="sku-add-value-ele" @click="handleAddSku(2, $index)">添加规格值</span>
          </div>
          <div class="sku-value-wrap">
            <div class="sku-value-list" v-for="(items, index) in item.attributes" :key="index">
              <el-input :class="['sku-input', {'is-error': items.isError}]" :size="size" v-model="items.value" @change="handleDataChange(items, item)"></el-input>
              <!-- 规格值 value -->
              <span class="delete-icon" @click="handleRemove(2, $index, index, item, items)">
                <i class="el-icon-close"></i>
              </span>
              <div v-if="item.havaIconChecked">
                <UploadImg v-model="items.imageUrl" :limitSize="{width: 340, height: 340}"></UploadImg>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 规格类型 -->

      <div style="margin-top: 10px;">
        <template v-if="addBtnDis || attributeParamList.length >= 3">
          <el-popover placement="top" title="" width="120" trigger="hover" content="最多支持三组规格">
            <el-button slot="reference" style="cursor: not-allowed;" @click="handleAddSku(1)" type="info" size="small"
                       icon="el-icon-plus">添加规格名</el-button>
          </el-popover>
        </template>
        <template v-else>
          <el-button :disabled="addBtnDis  || attributeParamList.length >= 3" @click="handleAddSku(1)" type="primary"
                     size="small" icon="el-icon-plus">添加规格名</el-button>
        </template>
      </div>
      <div class="error-tips">注意：添加、删除规格名都将重新置空规格明细中价格、库存等内容，请谨慎操作！</div>

      <!-- 规格明细 -->
      <div class="sku-detail">
        <div class="sku-label">规格明细：</div>
        <div class="sku-detail-table" v-if="skuDetailData && skuDetailData.length >= 1" v-loading="dataDealLoading">
          <div class="sku-row table-h">
            <div v-for="(item, index) in skuDetailTableHead" :key="index" class="sku-cell">
              <span>{{item}}</span>
            </div>
          </div>
          <div class="table-body">
            <div v-for="(item, index) in skuDetailData" :key="index" class="sku-row">
              <div class="sku-cell">
                <span>{{item.sp1}}</span>
              </div>
              <div class="sku-cell" v-if="attributeParamList.length >= 2">
                <span>{{item.sp2}}</span>
              </div>
              <div class="sku-cell" v-if="attributeParamList.length >= 3">
                <span>{{item.sp3}}</span>
              </div>
              <div class="sku-cell">
                <el-input v-model="item.usePointLimit" :disabled="priceType ==='3'" size="small"></el-input>
              </div>
              <div class="sku-cell">
                <!-- <el-input v-model="item.price" :disabled="priceType ==='2'" size="small"></el-input> -->
                <el-input v-model="item.costPrice*priceMultiple==0?'':item.costPrice*priceMultiple" disabled size="small"></el-input>
              </div>
              <div class="sku-cell">
                <el-input v-model="item.stock" size="small"></el-input>
              </div>
              <div class="sku-cell">
                <el-input v-model="item.weight" size="small"></el-input>
              </div>
              <div class="sku-cell">
                <el-input v-model="item.costPrice" size="small"></el-input>
              </div>
              <!-- <div class="sku-cell">
                <el-input v-model="item.sale" size="small"></el-input>
              </div> -->
              <div class="sku-cell sku-code">
                <el-input style="width: 140px;" v-model="item.skuCode" size="small"></el-input>
                <!-- <template v-else>
                  <ProductSn v-model="item.skuCode" size="small"></ProductSn>
                </template> -->
              </div>
            </div>
          </div>
          <div class="table-footer">
            <span>共{{skuDetailData.length}}条&nbsp; 批量设置：</span>
            <span v-for="item in batchSetupList" :key="item.key">
              <span class="pitch-ele disabled" v-if="item.key==='usePointLimit' && priceType === '3'">{{item.name}}</span>
              <span class="pitch-ele disabled" v-else-if="item.key==='price'  && priceType === '2' ">{{item.name}}</span>
              <span @click="handleBatchSet(item)" class="pitch-ele" v-else>{{item.name}}</span>
            </span>
            <span class="pitch-ele" @click="handleSetProductSn(true)">自动设置商品编码</span>
          </div>
        </div>

      </div>
      <!-- 规格明细 -->
    </div>
    <!-- 规格 -->

  </div>
</template>

<script>
import UploadImg from '@/components/Upload/imgSignleUpload'
// import ProductSn from '@/components/ProductSn'
import { GetProductSn } from '@/api/onlineMan'
import {priceMultiple} from "@/utils/rules"
export default {
  name: 'GoodSku',
  components: { UploadImg },
  data () {
    return {
      getSnLoading: false,
      productSnList: [], // 商品编码集合
      oneRequestNum: 60, // 获取商品编码 一次请求的条目数量
      size: 'medium',
      addBtnDis: false, // 是否再添加规格
      attributeParamList: [], // 规格类型数据
      skuDetailTableHead: [], // 规格明细表头
      // 积分 重量
      // tableHead: ['积分', '价格(元)', '库存', '重量(kg)', '成本价', '销量', '商品编码'],
      tableHead: ['积分', '价格(元)', '库存', '重量(kg)', '成本价', '商品编码'],
      // tableHeadKey: ['usePointLimit', 'price', 'stock', 'weight', 'costPrice', 'sale', 'skuCode'],
      tableHeadKey: ['usePointLimit', 'price', 'stock', 'weight', 'costPrice', 'skuCode'],
      batchSetupList: [
        { name: '积分', key: 'usePointLimit', regType: 1 },
        { name: '价格', key: 'price', regType: 2 },
        { name: '库存', key: 'stock', regType: 1 },
        { name: '重量', key: 'weight', regType: 2 },
        { name: '成本价', key: 'costPrice', regType: 2 }
        // { name: '销量', key: 'sale', regType: 1 }
      ],
      skuDetailData: [], // 规格类型组合数据
      skuDetailNowNum: 0, // 当前规格类型组合下的条目数量
      skuDetailDataNum: 600, // 规格类型组合数据限制条数
      skuValueLen: 40, // 每个规格名下规格值限制条数
      lastTimeSkuData: [], // 上一份规格类型组合数据
      dataDealLoading: false,
      skuCodeList: [],
      skuLen1List: [], // 第一规格名下规格值
      skuLen2List: [], // 第二规格名下规格值
      skuLen3List: [] // 第三规格名下规格值
    }
  },
  props: {
    priceType: {
      type: String,
      default: '1'
    },
    data: {
      type: Object,
      default: () => { }
    }
  },
  watch: {
    'priceType': function (val) {
      this.skuDetailData.forEach(e => {
        if (val === '2') e.price = '0'
        if (val === '3') e.usePointLimit = '0'
      })
    },
    'skuDetailData': {
      deep: true,
      handler: function (val) {
        this.upEmitData(val)
      }
    }
  },
  computed: {
    priceMultiple:function(){
      return priceMultiple;
    }
  },
  created () {
    this.getSn()
  },
  mounted () {
    this.dataHandle(this.data)
  },
  methods: {
    handleAddImg (val) {
      let info = this.attributeParamList[0]
      info.havaIconChecked = val
      this.$set(this.attributeParamList, 0, info)
    },
    // 数据对应
    dataHandle (val) {
      this.skuDetailTableHead = []
      if (val) {
        val.attributeParamList = val.attributeParamList || []
        val.pmsSkuStockVOList = val.pmsSkuStockVOList || []
        this.attributeParamList = val.attributeParamList
        this.attributeParamList.forEach((item, $index) => {
          if ($index === 0) {
            item.havaIconChecked = item.imageUrl !== ''
          } else {
            item.havaIconChecked = false
          }
          item.isError = false
          this.skuDetailTableHead.push(item.name)
        })
        this.skuDetailTableHead = this.skuDetailTableHead.concat(this.tableHead)

        this.skuDetailData = val.pmsSkuStockVOList || []
        this.lastTimeSkuData = val.pmsSkuStockVOList || []
      } else {
        this.attributeParamList = []
        this.skuDetailData = []
        this.handleSkuDetailData()
      }
    },
    // 添加规格名 规格值
    handleAddSku (type, $index) {
      // type 1 => 规格名 2 => 规格值 $index 父级的index index 子级的index
      const len = this.attributeParamList.length || 0
      const parentIndex = len ? (len + 1).toString() : '1'
      if (type === 1) {
        // 模板sku规格名数据
        const modelSku = {
          attributes: [{ imageUrl: '', value: '', cid: parentIndex + '-1' }],
          havaIcon: 0,
          havaIconChecked: false,
          name: '',
          sort: 0,
          isError: false,
          cid: parentIndex
        }
        if (len >= 3) {
          this.addBtnDis = true
          this.$message.warning('规格名最多只能添加三个！')
        } else {
          this.addBtnDis = false
          this.$nextTick(() => {
            this.attributeParamList.push(modelSku)
            if (len >= 3) {
              this.addBtnDis = true
            }
            this.handleSetTableHead()
            if (!this.isOverflow()) this.handleSkuDetailData()
          })
        }
      } else {
        // 模板sku规格值数据
        const indexLen = this.attributeParamList[$index].attributes.length
        if (indexLen >= this.skuValueLen) {
          this.$message.warning(`该规格名规格值最多${this.skuValueLen}个`)
        } else {
          const childIndex = indexLen ? (indexLen + 1).toString() : '1'
          const modelSkuVal = {
            isError: false,
            imageUrl: '',
            value: '',
            cid: ($index + 1).toString() + '-' + childIndex
          }
          this.attributeParamList[$index].attributes.push(modelSkuVal)
          if (!this.isOverflow()) {
            this.handleSkuDetailData(this.attributeParamList[$index].attributes)
          } else {
            this.attributeParamList[$index].attributes.pop()
          }
        }
      }
    },
    // 删除
    handleRemove (type, $index, index, item, items) {
      // type = 1 规格名删除
      this.isOverflow(1)
      if (type === 1) {
        this.addBtnDis = false
        // 获取规格名数据长度
        if (this.attributeParamList.length <= 1) {
          this.$message.warning('规格名不低于1个！')
        } else {
          this.attributeParamList.splice($index, 1)
          this.handleSetTableHead()
          this.handleSkuDetailData()
        }
      }

      // type = 2 规格值删除
      if (type === 2) {
        const len = item.attributes.length || 0
        if (len <= 1) {
          this.$message.warning('当前规格名下规格值不能低于1个！')
        } else {
          this.attributeParamList[$index].attributes.splice(index, 1)
          this.handleSkuDetailData()
        }
      }
    },
    // input change
    handleDataChange (val, val2) {
      const isName = val.hasOwnProperty('attributes')
      const tips = isName ? '规格名' : '规格值'
      let count = 0 // 出现次数
      let value = isName ? val.name : val.value
      let valList = isName ? this.attributeParamList : val2.attributes
      valList.forEach(e => {
        const eVal = isName ? e.name : e.value
        if (value && eVal === value) {
          count++
        }
      })

      this.$nextTick(() => {
        if (count > 1) {
          val.isError = true
          this.$message.warning(`${tips}存在重复值`)
        } else {
          val.isError = false
          if (isName) {
            this.handleSetTableHead()
          } else {
            this.skuDetailData.forEach(e => {
              if (e.cid1 === val.cid) {
                e.sp1 = value
              }
              if (e.cid2 === val.cid) {
                e.sp2 = value
              }
              if (e.cid3 === val.cid) {
                e.sp3 = value
              }
            })
          }
        }
      })
    },
    // 批量设置 规格明细数据
    handleBatchSet (row, type, title) {
      const tips = '格式不正确'
      const priceReg = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/ // 含零的正整数正则 小数两位
      const sortReg = /^([1-9]\d*|[0]{1,1})$/ // 含零的正整数正则
      let inputPatternReg = ''

      const inputTitle = row.name
      const inputErrorMessage = row.name + tips
      const key = row.key || ''
      if (row.regType === 1) inputPatternReg = sortReg
      if (row.regType === 2) inputPatternReg = priceReg

      this.$prompt('', `批量设置${inputTitle}`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputValue: '',
        inputPattern: inputPatternReg,
        inputErrorMessage: inputErrorMessage
      }).then(({ value }) => {
        this.skuDetailData.forEach(item => {
          item[key] = value
        })
      }).catch(() => { })
    },
    // 设置表头
    handleSetTableHead () {
      this.skuDetailTableHead = []
      const heads = this.attributeParamList.map(e => e.name)
      this.skuDetailTableHead = heads.concat(this.tableHead)
    },
    // 规格明细数据处理
    handleSkuDetailData (item) {
      this.dataDealLoading = true
      this.lastTimeSkuData = JSON.parse(JSON.stringify(this.skuDetailData)) // 记录改变的规格明细数据
      this.skuDetailData = []
      try {
        // 列举出现的组合
        let dataArr = []
        this.skuLen1List.forEach((v1, index1) => {
          if (this.skuLen2List.length >= 1) {
            this.skuLen2List.forEach((v2, index2) => {
              if (this.skuLen3List.length >= 1) {
                this.skuLen3List.forEach((v3, index3) => {
                  dataArr.push(this.skuDetailDataAssign(v1, v2, v3))
                })
              } else {
                dataArr.push(this.skuDetailDataAssign(v1, v2))
              }
            })
          } else {
            dataArr.push(this.skuDetailDataAssign(v1))
          }
        })
        // 相同规格赋值
        dataArr.forEach((e, index) => {
          if (this.lastTimeSkuData && this.lastTimeSkuData.length > 0) {
            this.lastTimeSkuData.forEach(i => {
              // 存在第三规格名
              if (this.skuLen3List.length > 0) {
                if (!e.sp3 || !e.sp2 || !e.sp1) {
                  e.skuCode = this.productSnList[index]
                } else if (e.sp1 === i.sp1 && e.sp2 === i.sp2 && e.sp3 === i.sp3) {
                  e.usePointLimit = i.usePointLimit
                  e.weight = i.weight
                  e.price = i.price
                  e.costPrice = i.costPrice
                  e.stock = i.stock
                  e.skuCode = i.skuCode || this.productSnList[index]
                }
              } else if (!this.skuLen3List || this.skuLen3List.length === 0) {
                // 第三规格名 不存在
                if (!e.sp2 || !e.sp1) {
                  e.skuCode = this.productSnList[index]
                } else if (e.sp1 === i.sp1 && e.sp2 === i.sp2) {
                  e.usePointLimit = i.usePointLimit
                  e.weight = i.weight
                  e.price = i.price
                  e.costPrice = i.costPrice
                  e.stock = i.stock
                  e.skuCode = i.skuCode || this.productSnList[index]
                }
              } else if (!this.skuLen2List || this.skuLen2List.length === 0) {
                // 第二规格名 不存在
                if (!e.sp1) {
                  e.skuCode = this.productSnList[index]
                } else if (e.sp1 === i.sp1) {
                  e.usePointLimit = i.usePointLimit
                  e.weight = i.weight
                  e.price = i.price
                  e.costPrice = i.costPrice
                  e.stock = i.stock
                  e.skuCode = i.skuCode
                }
              } else {
              }
            })
          } else {
            e.skuCode = this.productSnList[index]
          }
        })

        this.skuDetailData = dataArr
        this.dataDealLoading = false
      } catch (error) {
        this.dataDealLoading = false
      }
    },
    // 规格明细赋值
    skuDetailDataAssign (v1, v2, v3) {
      let itemInfo = {
        sp1: v1.value,
        cid1: v1.cid,
        sp2: v2 ? v2.value : '',
        cid2: v2 ? v2.cid : '',
        sp3: v3 ? v3.value : '',
        cid3: v3 ? v3.cid : '',
        usePointLimit: '',
        price: '',
        costPrice: '',
        weight: '',
        stock: '',
        sale: '',
        skuCode: ''
      }
      return itemInfo
    },
    // 是否溢出 判断规格数量是否超过 this.skuDetailDataNum 默认 600条 当前规格值 删除 后续不操作
    isOverflow (type) {
      // type 是否判断 1 不判断 其他 判断
      this.skuLen1List = this.retrunArr(1) // 第一规格名下规格值
      const skuLen1ListLen = this.skuLen1List.length > 1 ? this.skuLen1List.length : 1
      this.skuLen2List = this.retrunArr(2) // 第二规格名下规格值
      const skuLen2ListLen = this.skuLen2List.length > 1 ? this.skuLen2List.length : 1
      this.skuLen3List = this.retrunArr(3) // 第三规格名下规格值
      const skuLen3ListLen = this.skuLen3List.length > 1 ? this.skuLen3List.length : 1
      const num = skuLen1ListLen * skuLen2ListLen * skuLen3ListLen // 当前组合可能的条目数量
      if (!type) {
        // 数量超过600条 当前规格值 后续不操作
        if (num > this.skuDetailDataNum) {
          this.$message.warning(`规格明细数量不允许超过${this.skuDetailDataNum}条`)
          return true
        } else {
          this.skuDetailNowNum = num
          // 当前组合可能的条目数量 要大于商品编码集合的条目数
          // 请求条目数量 this.oneRequestNum(50)条一次请求
          // 差值如果小于this.oneRequestNum(50) 以this.oneRequestNum(50)条为请求条数
          // 大于this.oneRequestNum(50) 为差值数为请求条数
          if (num > this.productSnList.length) {
            const len = num - this.productSnList.length
            const count = len <= this.oneRequestNum ? len : this.oneRequestNum
            this.getSn(count)
          }
          return false
        }
      }
    },
    // 判断是否存在 attributes
    retrunArr (index) {
      if (!this.attributeParamList || this.attributeParamList.length <= 0) return []
      const skuValList = this.attributeParamList[index - 1] && this.attributeParamList[index - 1].attributes && this.attributeParamList[index - 1].attributes.length >= 1 ? this.attributeParamList[index - 1].attributes : []
      return skuValList
    },
    handleSetProductSn (force) {
      // 存在force 全部重新赋值
      this.dataDealLoading = true
      if (force) {
        const num = this.skuDetailData.length - this.productSnList
        if (num > 0) this.getSn(num, false)
        this.$nextTick(() => {
          this.skuDetailData.forEach((e, index) => {
            e.skuCode = this.productSnList[index]
          })
        })
      } else {
        this.$nextTick(() => {
          this.skuDetailData.forEach((e, index) => {
            if (!e.skuCode) {
              e.skuCode = this.productSnList[index]
            }
          })
        })
      }
      setTimeout(() => {
        this.dataDealLoading = false
      }, 1 * 1000)
    },
    getSn (num, noAssign) {
      // num 请求条目数量 noAssign 不需要赋值
      const len = num || this.oneRequestNum
      GetProductSn({ count: len, type: 2 }).then(res => {
        if (num) {
          this.productSnList = this.productSnList.concat(res.data.list)
        } else {
          this.productSnList = res.data.list || []
        }
        this.getSnLoading = false
        if (!noAssign) this.handleSetProductSn()
      }).catch(() => {
        this.getSnLoading = false
      })
    },
    // 上传数据
    upEmitData (val) {
      let data = {
        attributeParamList: this.attributeParamList,
        pmsSkuStockVOList: val || this.skuDetailData
      }
      data.attributeParamList.forEach((e, index) => {
        e.attributes.forEach(item => {
          if (index > 0 && item.imageUrl) {
            item.imageUrl = ''
          }
        })
        e.attributeValueList = e.attributes
      })
      this.skuCodeList = data.pmsSkuStockVOList.map(e => e.skuCode)
      this.$emit('upEmitData', data)
    }
  }
}

</script>
<style lang='scss' scoped>
@import '@/styles/sku.scss';
</style>
